package com.masterrabbit.gyf.Service;

import com.alibaba.fastjson2.JSONObject;
import com.masterrabbit.gyf.domain.Coupons;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class TicketService {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private DefaultRedisScript<String> ticketScript;


    /**
     * 初始化票列表
     *
     * @param tickets 票的编号列表
     */
    public void initTickets(List<String> tickets,long seconds,String createTime,int MerchantId) {
        String key = "tickets:"+MerchantId+":"+createTime;
        redisTemplate.opsForList().rightPushAll(key,tickets); // 将票的编号添加到列表中
        //开始设置过期时间
        System.out.println("打印一下最后的数据:"+tickets.get(0));
        redisTemplate.expire(key, seconds, TimeUnit.SECONDS);//设置过期时间

    }

    /**
     * 抢票操作
     *
     * @return 票的编号，如果返回 null 则表示票已售罄
     */
    public String grabTicket(String key) {
//        String key = "tickets";
        // 执行 Lua 脚本
        return redisTemplate.execute(ticketScript, Collections.singletonList(key));
    }

}
